package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemdiaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private WemdiaFeign wemdiaFeign;
    @Autowired
    private ArticleFeign articleFeign;


    /**
     * 查询列表
     *
     * @param authDTO
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDTO authDTO) {
        // 1 参数检查
        if (authDTO == null) {
            CustException.cust(AppHttpCodeEnum.TOKEN_INVALID, "无效的参数");
        }
        authDTO.checkParam();
        // 2 条件查询
        Page page = new Page(authDTO.getPage(), authDTO.getSize());
        LambdaQueryWrapper<ApUserRealname> lambdaQuery = Wrappers.<ApUserRealname>lambdaQuery();
        if (authDTO.getStatus() != null) {
            lambdaQuery.eq(ApUserRealname::getStatus, authDTO.getStatus());
        }
        IPage result = this.page(page, lambdaQuery);

        PageResponseResult pageResponseResult = new PageResponseResult(authDTO.getPage(), authDTO.getSize(), result.getTotal(), result.getRecords());

        // 3 返回结果
        return pageResponseResult;
    }

    /**
     * 根据状态进行审核
     *
     * @param dto
     * @param status 2 审核失败   9 审核成功
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        // 1.参数校验
        if (dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "id不能为空");
        }
        //2 查询当前认证用户是否在 APP端有当前用户
        ApUserRealname userRealname = getOne(
                Wrappers.<ApUserRealname>lambdaQuery().eq(ApUserRealname::getId, dto.getId()));
        if (userRealname == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证信息不存在");
        }
        if (!AdminConstants.WAIT_AUTH.equals(userRealname.getStatus())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"当前不是可审核的状态");
        }
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getId, dto.getId()));
        if (apUser == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的用户不存在");
        }
        //3 更新认证用户信息
        userRealname.setStatus(status);
        userRealname.setUpdatedTime(new Date());
        if (dto.getMsg()!=null){
            userRealname.setReason(dto.getMsg());
        }
        this.updateById(userRealname);
        //4 认证状态如果为 通过
        if (AdminConstants.PASS_AUTH.equals(status)){
            //4.1 创建自媒体账户
           WmUser wmUser = createWemedia(apUser);
            //4.2 创建作者信息
            createAuthor(apUser,wmUser);
//            System.out.println(1/0);
        }
        //5 返回结果
        return ResponseResult.okResult();
    }

    /**
     * 创建作者信息
     * @param apUser
     * @param wmUser
     */
    private void createAuthor(ApUser apUser, WmUser wmUser) {
        //1 检查是否成功调用
        ResponseResult<ApAuthor> responseResult = articleFeign.findByUserId(apUser.getId());
        //2. 检查作者信息是否已经存在
        ApAuthor apAuthor = responseResult.getData();
        if (apAuthor != null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        //3. 添加作者信息
        apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(2);
        apAuthor.setUserId(apUser.getId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        //4. 结果失败，抛出异常
        ResponseResult save = articleFeign.save(apAuthor);
        if (save.getCode() != 0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    /**
     * 创建自媒体账户
     * @param apUser
     * @return
     */
    private WmUser createWemedia(ApUser apUser) {
        //1 查询自媒体账号是否存在（APP端用户密码和自媒体密码一致）
        ResponseResult<WmUser> result = wemdiaFeign.findByName(apUser.getName());
        if (!result.checkCode()){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,result.getErrorMessage());
        }
        WmUser wmUser = result.getData();
        if (wmUser != null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());

        ResponseResult<WmUser> save = wemdiaFeign.save(wmUser);
        if (save.getCode() != 0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }
        return wmUser;
    }
}
